<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2019/10/22
 * Time: 9:34 下午
 */

namespace addons\unishop\controller;

use addons\unishop\extend\Hashids;
use app\common\controller\Api;
use app\common\library\Upload;
use tests\thinkphp\library\think\dbTest;
use think\Cache;
use think\Db;
use think\Lang;
use think\Config;
/**
 * 基础类
 * @ApiInternal
 */
class Base extends Api
{
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 允许频繁访问的接口（方法格式：小写）
     * @var array
     */
    protected $frequently = [];

    public function _initialize()
    {
        parent::_initialize();

        $this->loadUniShopLang();

        $this->limitVisit();
    }

    /**
     * 限制接口访问频率
     * @param int $millisecond
     * @ApiInternal
     */
    public function limitVisit($millisecond = 200) {
        $millisecond = $this->request->request('millisecond', $millisecond);

        // 限制200毫秒 防止1秒两刀 （双击甚至三击，同一时间导致接口请求两次以上）
        $action = $this->request->action();
        if (!in_array($action, $this->frequently) && $this->auth && $this->auth->isLogin() && $millisecond > 0) {
            $controller = $this->request->controller();
            if (Cache::has($controller.'_'.$action.'_'.$this->auth->id)) {
                if (Cache::get($controller.'_'.$action.'_'.$this->auth->id) + $millisecond > \addons\unishop\model\Config::getMillisecond()) {
                    $this->error(__('Frequent interface requests'));
                }
            }
            Cache::set($controller.'_'.$action.'_'.$this->auth->id, \addons\unishop\model\Config::getMillisecond(), 1);
        }
    }

    /**
     * 加载语言文件
     */
    protected function loadUniShopLang()
    {
        $route = $this->request->route();
        $lang = $this->request->header('lang') ?: 'zh-cn';
        $path = ADDON_PATH . $route['addon'] . '/lang/' . $lang . '/' . str_replace('.', '/', $route['controller']) . '.php';
        Lang::load(ADDON_PATH . $route['addon'] . '/lang/'.$lang.'.php'); // 默认语言包
        Lang::load($path);
    }


    /**
     * 地址信息
     * */

    public function getaddress(){

        $info=Db::name('aa_address')->find();


        $this->success('地址信息',$info);
    }


    /**
     * 上传文件
     * @ApiMethod (POST)
     * @param File $file 文件流
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                //合并分片文件
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                //删除冗余的分片文件
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                //上传分片文件
                //默认普通上传文件
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            //默认普通上传文件
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }



    /**
     * 联系信息
     * */

    public function getcontact(){
        $info=Db::name('aa_contact')->find();

        $info['image']=cdnurl($info['image'],true);
        $this->success('地址信息',$info);
    }


    /**
     * 服务 条款 协议
     */
    public function getagreement(){
        $info=Db::name('aa_agreement')->find();
        $this->success('服务条款 协议',$info);
    }

    /**
     * 优惠券
     */

    public function getcoupon(){

        $info=Db::name('unishop_coupon')->where(['switch'=>1])->select();

        foreach ($info as &$key){

            $key['starttime']=date('Y-m-d H:i',$key['starttime']);
            $key['endtime']=date('Y-m-d H:i',$key['endtime']);

        }

        $this->success('服务条款 协议',$info);

    }


    public function getcouponimg(){

        $info=Db::name('aa_quanimg')->find();

        $info['image']=cdnurl($info['image'],true);

        $this->success('服务条款 协议',$info);

    }


    /**
     * 首页分类
     */
        public function getindexcate(){


            $info=Db::name('aaindexcate')->order('weigh desc')->select();

            $this->success('首页分类',$info);

        }


     /**
      * 分类列表
      */
     public function getindexlistbyid(){

         $id=$this->request->param('id');


         $info=Db::name('aaindexgood')->where(['aaindexcate_id'=>$id])->select();


         foreach ($info as &$key){


             $coun=Db::name('unishop_product')->where('id','in',$key['unishop_product_ids'])->sum('stock');

             $key['image']=cdnurl($key['image'],true);
             $key['count']=$coun;
         }

         $this->success('首页分类1',$info);


     }

    /**
     */
     public function getgoodbyid(){

         $id=$this->request->param('id');

         $info=Db::name('aaindexgood')->where(['id'=>$id])->find();

         $info['image']=cdnurl($info['image'],true);


         $map['id']=['in',$info['unishop_product_ids']];

         $order=$this->request->param('order');

         if ($order==1){
             $order_t='sales_price desc';
         }else if ($order==2){
             $order_t='sales_price asc';
         }else{
             $order_t='id desc';
         }

         $version=$this->request->param('version');

         if ($version&&$version!='全部'){
             $map['version']=['eq',$version];
         }

         $old=$this->request->param('old');
         if ($old&&$old!='全部'){
             $map['old']=['eq',$old];
         }

         $memory=$this->request->param('memory');
         if ($memory&&$memory!='全部'){
             $map['memory']=['eq',$memory];
         }


         $goods=Db::name('unishop_product')->where($map)
             ->order($order_t)
             ->field('id,image,title,sales_price,old,battery,charge,memory,notlocks,version,showtit')->select();

         foreach ($goods as &$kk){

             $kk['product_id'] = Hashids::encodeHex($kk['id']);
             $kk['image'] = cdnurl($kk['image'],true);
         }

         $info['goods']=$goods;

         $this->success('首页分类',$info);

     }



     /**\
      * 内存 成色 版本
      *
      */
    public function getselectinfo(){


        $version=['全部','国航','港版','美版','日版'];
        $quality=['全部','全新','99新','98新','95新','9新','85新','8新'];
        $ram=['全部','16G','32G','64G','128G','256G','512G','1T'];


        $this->success('首页分类',['version'=>$version,'old'=>$quality,'memory'=>$ram]);

    }

    /**\
     * 内存 成色 版本
     *
     */
    public function toverify(){

        // 1=已审核  0=审核

        $this->success('首页分类',['verify'=>1]);

    }


}
